<?php
// +----------------------------------------------------------------------
// | HkCms
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2019 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

namespace libs\system;

use common\model\Cache as CacheModel;

class Cache
{
    /**
     * 连接缓存系统
     * @return Cache
     */
    static public function getInstance()
    {
        static $systemHandier;
        if (empty($systemHandier)) {
            $systemHandier = new Cache();
        }
        return $systemHandier;
    }

    /**
     * 获取缓存
     * @param $name
     * @return bool|null
     */
    public function get($name)
    {
        $cache = cache($name);
        if (!empty($cache)) {
            return $cache;
        } else {
            // 尝试生成缓存
            return $this->runUpdate($name);
        }
    }

    /**
     * 写入缓存
     * @param string $name 缓存变量名
     * @param string|array $value 存储数据
     * @param integer $expire 有效时间（秒）
     * @return boolean
     */
    public function set($name, $value, $expire = null) {
        return cache($name, $value, $expire);
    }

    /**
     * 删除缓存
     * @param string $name 缓存变量名
     * @return boolean
     */
    public function remove($name) {
        return cache($name, NULL);
    }

    /**
     * 更新缓存
     * @param $name
     * @return bool|mixed
     */
    public function runUpdate($name)
    {
        // 没有安装的情况下不缓存。
        if (!hkcms_is_installed()) {
            return false;
        }
        if (empty($name)) {
            return false;
        }

        $cacheModel = new CacheModel;

        // 查询缓存key
        $cacheList = $cacheModel->where(['key'=>$name])->order(['id'=>'desc'])->select();

        if ($cacheList->isEmpty()) {
            return false;
        }

        foreach ($cacheList->toArray() as $cache) {
            $cacheModel->runUpdate($cache);
        }
        
        // 返回更新的数据
        return cache($name);
    }
}